﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Data;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using DaInterFace;
using DaInterFace.Mobile;
using DaInterFace.PDA;
using DaInterFace.SYN;

using DaFunction.Mobile;
using DaFunction.PDA;
using DaFunction.SYN;
using DaFunction.Transfer;
using System.Reflection;

namespace DaFunction
{
    public class DaClass
    {
        private const int MAX_LINE = 1000;
        private IConfig daConfig;
        private IDataBase daData;
        private IMobile daMobile;
        private IPDA daPDA;
        private ISYN daSYN;


        public IConfig DaConfig { get { return daConfig; } }
        public IDataBase DaData { get { return daData; } }
        public IMobile DaMobile { get { return daMobile; } }
        public IPDA DaPDA { get { return daPDA; } }
        public ISYN DaSYN { get { return daSYN; } }

        public DaClass()
        {
            daConfig = new Config();

            daData = new DataBase(daConfig.Get("Page00_Conn"));
            daMobile = new DaFunction.Mobile.Mobile(daData, daConfig);
            daPDA = new DaFunction.PDA.PDA(daData, daConfig);
            daSYN = new DaFunction.SYN.SYN(daData, daConfig);

        }

        public void Init()
        {
            TransferLoad();

            Thread threadMobile = new Thread(MobileLoad);
            threadMobile.IsBackground = true;
            threadMobile.Name = "手机端服务";
            threadMobile.Start();

            Thread threadPDA = new Thread(PDALoad);
            threadPDA.IsBackground = true;
            threadPDA.Name = "手持设备服务";
            threadPDA.Start();

            Thread threadSYN = new Thread(SYNLoad);
            threadSYN.IsBackground = true;
            threadSYN.Name = "数据同步接口服务";
            threadSYN.Start();

            Thread dataTimer = new Thread(DataTimer);
            dataTimer.IsBackground = true;
            dataTimer.Name = "定时数据执行器";
            dataTimer.Start();

            daData.Test();
        }

        private void DataTimer()
        {
            Dictionary<string, SetOfBook> books = DaData.GetAccounts();
            while (true)
            {
                //foreach (SetOfBook book in books.Values)
                //{
                //    Recordset ds = DaData.ExeProcedure(book.FNumber, "EXEC KEW_SALES_CHECKREADJUST");
                //    if (!ds.Enable)
                //    {
                //        DaData.Message(MessageType.Error, String.Format("账套{0}执行定时数据时出现错误:{1}", book.FNumber, ds.Message));
                //    }
                //}

                Thread.Sleep(60000); //每分钟执行一次
            }
        }

        private void MobileLoad()
        {
            MobileApi.DaMobile = daMobile;
            Uri baseAddress = new Uri(String.Format("http://localhost:{0}/MobileService.svc/", daConfig.Get("Page01_Port")));
            ServiceHost host = new ServiceHost(typeof(MobileApi), baseAddress);

            host.AddServiceEndpoint(typeof(IMobileApi), new BasicHttpBinding(), "");
            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            behavior.HttpGetEnabled = true;
            behavior.HttpGetUrl = new Uri(String.Format("http://localhost:{0}/MobileService.svc/", daConfig.Get("Page01_Port")));
            host.Description.Behaviors.Add(behavior);

            try
            {
                host.Open();
                daMobile.Message(MessageType.Note, "手机服务端加载成功,访问地址：" + baseAddress.AbsoluteUri);
            }
            catch (Exception ex)
            {
                daMobile.Message(MessageType.Error, "手机服务端加载失败:" + ex.Message);
            }
        }

        private void PDALoad()
        {
            PDAApi.DaPDA = daPDA;
            Uri baseAddress = new Uri(String.Format("http://localhost:{0}/PDAService.svc/", daConfig.Get("Page02_Port")));
            ServiceHost host = new ServiceHost(typeof(PDAApi), baseAddress);

            host.AddServiceEndpoint(typeof(IPDAApi), new BasicHttpBinding(), "");
            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            behavior.HttpGetEnabled = true;
            behavior.HttpGetUrl = new Uri(String.Format("http://localhost:{0}/PDAService.svc/", daConfig.Get("Page02_Port")));
            host.Description.Behaviors.Add(behavior);

            try
            {
                host.Open();
                daPDA.Message(MessageType.Note, "手持设备服务加载成功,访问地址：" + baseAddress.AbsoluteUri);
            }
            catch (Exception ex)
            {
                daPDA.Message(MessageType.Error, "手持设备服务加载失败:" + ex.Message);
            }
        }

        //private void LoadBaseInfo()
        //{
        //    Dictionary<String, SetOfBook> setBook = daData.GetAccounts();
        //    Recordset rs = null;
        //    foreach (SetOfBook sb in setBook.Values)
        //    {
        //        try
        //        {
        //            daSYN.BaseDictionary.Add(sb.FNumber, new Dictionary<string, Dictionary<string, BaseInfo>>());
        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText SID FROM KEW_SalesConfigEntry WHERE FText!=''");

        //            daSYN.BaseDictionary[sb.FNumber].Add("A01", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A01"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-销售计量方案（A01）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText SID FROM KEW_ProductsBagRuleEntry WHERE FText!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A02", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A02"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-销售袋装标准（A02）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText SID FROM KEW_ProductsEntry WHERE FText!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A03", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A03"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-产品（A03）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FItemID FID,FHomePage SID FROM t_Organization WHERE FHomePage!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A04", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A04"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-客户（A04）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText3 SID FROM KEW_SalesGuests WHERE FText3!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A05", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A05"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-客户档案（A05）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText1 SID FROM KEW_SalesAccount WHERE FText1!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A06", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A06"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-销售账户（A06）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText2 SID FROM KEW_SaleOrderQty WHERE FText2!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A07", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A07"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-销售提货单（A07）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText SID FROM KEW_SalesCash WHERE FText!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A08", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A08"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-销售收款（A08）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText2 SID FROM KEW_SalesReadjust WHERE FText2!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A09", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A09"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-销售调价（A09）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText2 SID FROM KEW_SalesRebate WHERE FText2!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A10", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A10"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-销售返利（A10）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            ///采购
        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText SID FROM KEW_PurchConfigEntry WHERE FText!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A31", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A31"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-采购计量方案（A31）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText SID FROM KEW_PurchItemEntry WHERE FText!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A32", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A32"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-大宗原料（A32）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FItemID FID,FHomePage SID FROM t_Supplier WHERE FHomePage!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A33", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A33"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-供应商（A33）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //            rs = daData.ExeProcedure(sb.FNumber, "SELECT FID,FText SID FROM KEW_PurchOrderQty WHERE FText!=''");
        //            daSYN.BaseDictionary[sb.FNumber].Add("A34", new Dictionary<string, BaseInfo>());
        //            foreach (DataRow row in rs.Data.Tables[0].Rows)
        //            {
        //                daSYN.BaseDictionary[sb.FNumber]["A34"].Add(row["SID"].ToString(), new BaseInfo(row["FID"].ToString()));
        //            }
        //            daSYN.Message(MessageType.Note, String.Format("成功加载账套{0}-采购订货单（A34）:{1}条", sb.FNumber, rs.Data.Tables[0].Rows.Count));

        //        }
        //        catch (Exception ex)
        //        {
        //            daSYN.BaseDictionary.Remove(sb.FNumber);
        //            daSYN.Message(MessageType.Error, String.Format("加载账套{0}基础资料时发生错误:{1}",sb.FNumber, ex.Message));
        //        }
        //    }
        //}

        private void SYNLoad()
        {

            SYNApi.DaSYN = daSYN;
            Uri baseAddress = new Uri(String.Format("http://localhost:{0}/SYNService.svc/", daConfig.Get("Page03_Port")));
            ServiceHost host = new ServiceHost(typeof(SYNApi), baseAddress);

            host.AddServiceEndpoint(typeof(ISYNApi), new BasicHttpBinding(), "");
            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            behavior.HttpGetEnabled = true;
            behavior.HttpGetUrl = new Uri(String.Format("http://localhost:{0}/SYNService.svc/", daConfig.Get("Page03_Port")));
            host.Description.Behaviors.Add(behavior);

            try
            {
                host.Open();
                daSYN.Message(MessageType.Note, "数据同步接口加载成功,访问地址：" + baseAddress.AbsoluteUri, 0);
            }
            catch (Exception ex)
            {
                daSYN.Message(MessageType.Error, "数据同步接口加载失败:" + ex.Message, 0);
            }
        }

        private void TransferLoad()
        {
            //PDAApi.DaPDA = daPDA;
            Uri baseAddress = new Uri(String.Format("http://localhost:{0}/TransferService.svc", 18730));
            ServiceHost host = new ServiceHost(typeof(TransferApi), baseAddress);

            host.AddServiceEndpoint(typeof(ITransferApi), new BasicHttpBinding(), "");
            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            behavior.HttpGetEnabled = true;
            behavior.HttpGetUrl = new Uri(String.Format("http://localhost:{0}/TransferService.svc", 18730));
            host.Description.Behaviors.Add(behavior);

            try
            {
                host.Open();
                daData.Message(MessageType.Note, "数据中转已开启：" + baseAddress.AbsoluteUri);
            }
            catch (Exception ex)
            {
                daData.Message(MessageType.Error, "数据中转启动失败:" + ex.Message);
            }
        }
    }
}
